package controller;

import java.io.IOException;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.User;

import core.*;

public class ChangeProfile extends HttpServlet {
	private static final long serialVersionUID = 1L;
	PgSQL db = PgSQL.getInstance();
	ResultSet rs = null;
	String Query = "";

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		CurrentUser user = new CurrentUser(request);
		if (!user.isLoggedIn()){
			View.showMessage(request, response, "Please Login First", "Login");
			return;
		}
		
		User u = new User();
		int uid = user.getUid();
		
		if (uid > 0) {
			try {
				Query = "SELECT * FROM qz_user WHERE uid=?";
				PreparedStatement ps = db.prepareStatement(Query);
				ps.setInt(1, uid);
				rs = ps.executeQuery();
				if (rs.next()) {
					u.setUid(rs.getInt(1));
					u.setUsername(rs.getString(2));
					u.setEmail(rs.getString(3));
					u.setPassword(rs.getString(4));
					u.setGroupId(rs.getInt(5));
				}
			} catch (Exception e) {
				e.printStackTrace();
			}		
			request.setAttribute("user", u);
			View.show(request, response, "change_profile");
		}
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		CurrentUser user = new CurrentUser(request);
		if (!user.isLoggedIn()){
			View.showMessage(request, response, "Please Login First", "Login");
			return;
		}

		String username = request.getParameter("uname");
		String old_pwd = request.getParameter("opwd");
		String new_pwd1 = request.getParameter("npwd1");
		String new_pwd2 = request.getParameter("npwd2");

		if (username == null || username.isEmpty() || old_pwd == null || old_pwd.isEmpty()) {
			View.showMessage(request, response, "Please fill in all box blow", "back");
		}
		
		if (new_pwd1 == null || new_pwd2 == null || !new_pwd1.equals(new_pwd2)) {
			View.showMessage(request, response, "The new password you just inputed are different!", "back");
		}
		
		try {
			if (user.changePassword(old_pwd, new_pwd1)) {
				View.showMessage(request, response, "Change Successfully~~", "back");
			}else{
				View.showMessage(request, response, "Old password Wrong", "back");
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
